<template>
    <div class="preview-video">
        <video controls ref="videoRef" @loadedmetadata="onLoad" @error="onError">
            <source :src="url" :type="getMimeType(file.name)" />
            您的浏览器不支持视频播放。
        </video>
        <div class="video-info" v-if="videoInfo">
            {{ videoInfo.width }} × {{ videoInfo.height }} ({{ formatFileSize(file.size) }})
        </div>
    </div>
</template>

<script setup>
import { ref } from 'vue'

const props = defineProps({
    file: {
        type: Object,
        required: true
    },
    url: {
        type: String,
        required: true
    }
})

const emit = defineEmits(['loaded', 'error'])

const videoRef = ref(null)
const videoInfo = ref(null)

const getFileExtension = (fileName) => {
    if (!fileName || typeof fileName !== 'string') return ''
    return fileName.split('.').pop().toLowerCase()
}

const getMimeType = (fileName) => {
    const ext = getFileExtension(fileName)
    const mimeTypes = {
        mp4: 'video/mp4',
        avi: 'video/x-msvideo',
        mkv: 'video/x-matroska',
        mov: 'video/quicktime',
        wmv: 'video/x-ms-wmv',
        flv: 'video/x-flv',
        webm: 'video/webm',
    }
    return mimeTypes[ext] || 'video/mp4'
}

const formatFileSize = (size) => {
    if (size === undefined || size === null || size === 0) return '0 Bytes'
    if (isNaN(size)) return '未知大小'
    const k = 1024
    const sizes = ['Bytes', 'KB', 'MB', 'GB']
    const i = Math.floor(Math.log(size) / Math.log(k))
    return parseFloat((size / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
}

const onLoad = () => {
    if (videoRef.value) {
        videoInfo.value = {
            width: videoRef.value.videoWidth,
            height: videoRef.value.videoHeight,
        }
        emit('loaded', videoInfo.value)
    }
}

const onError = (e) => {
    emit('error', e)
}
</script>

<style scoped>
.preview-video {
    width: 100%;
    height: 100%;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    overflow: auto;
}

.preview-video video {
    max-width: 100%;
    max-height: 100%;
    outline: none;
    object-fit: contain;
}

.video-info {
    margin-top: 10px;
    font-size: 14px;
    color: #666;
}
</style>